import type { LocaleDefinition } from '..';

/**
 * Merges the given locales into one locale.
 * The locales are merged in the order they are given.
 * The first locale that provides an entry for a category will be used for that.
 * Mutating the category entries in the returned locale will also mutate the entries in the respective source locale.
 *
 * @param locales The locales to merge.
 *
 * @returns The newly merged locale.
 *
 * @example
 * import { de_CH, de, en, mergeLocales } from '@faker-js/faker';
 *
 * const de_CH_with_fallbacks = mergeLocales([ de_CH, de, en ]);
 *
 * @since 8.0.0
 */
export function mergeLocales(locales: LocaleDefinition[]): LocaleDefinition {
  const merged: LocaleDefinition = {};

  for (const locale of locales) {
    for (const key in locale) {
      const value = locale[key];
      if (merged[key] === undefined) {
        merged[key] = { ...value };
      } else {
        merged[key] = { ...value, ...merged[key] };
      }
    }
  }

  return merged;
}
